package com.wswy.wzcx.ui.fkdj

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.Html
import android.text.TextUtils
import android.view.View
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.ProgressDialogObserver
import com.che.libcommon.utils.ToastUtils
import com.che.libcommon.utils.optional.Optional
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.api.ConfigsKt
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.model.PaymentOrder
import com.wswy.wzcx.model.coupon.CouponModel
import com.wswy.wzcx.model.coupon.CouponResp
import com.wswy.wzcx.model.pay.PayStyleModel
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.module.pay.PayManager
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ModuleActivity
import com.wswy.wzcx.ui.coupon.ChooseCouponFragment
import com.wswy.wzcx.ui.dialog.FullHintAlertDialog
import com.wswy.wzcx.ui.dialog.WarningDialog
import com.wswy.wzcx.ui.fragment.FKDJResultFragment
import com.wswy.wzcx.ui.web.WebViewActivity
import com.wswy.wzcx.utils.ImageUtils
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_fkdj_fine_pay.*
import java.io.File

/**
 * 罚款代缴-填单-支付
 */
@Deprecated("")
class FinePaymentFragment : CBaseFragment() {

    companion object {
        private const val REQ_CHOOSE_COUPON = 106
    }

    private lateinit var fineViewModel: FineViewModel

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_fkdj_fine_pay
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        fineViewModel = provideViewModelFromActivity(FineViewModel::class.java)

        if (fineViewModel.getFineLiveData().value?.fromQuery() == true){
            //接口查询到罚单信息
            childFragmentManager.beginTransaction().replace(R.id.fl_fine_content,FineInfoFragment(),"readonly_fine").commitNow()

        }else{
            childFragmentManager.beginTransaction().replace(R.id.fl_fine_content,FineEditFragment(),"readonly_edit").commitNow()

        }

        group_fast_deal.onClick {

            switch_quick_payment.run {
                toggle()

                if (isChecked){
                    tv_fast_deal_desc.visibility = View.VISIBLE

                    sendClickEvent(StatisticsId.fkdj_urgent_open)

                }else{
                    tv_fast_deal_desc.visibility = View.GONE

                    sendClickEvent(StatisticsId.fkdj_urgent_close)

                }

                fineViewModel.setQuickDeal(isChecked)

            }

        }


        btn_pay.onClick {

            updatePayType(pay_layout.getPayStyle())

            checkPay()
        }



        initData()
    }



    private fun initData(){

        tv_fine_protocol.text = Html.fromHtml(getString(R.string.fkdj_protocol))
        tv_send_sms_hint.text = getString(R.string.fine_order_info_send,DataCenter.get().userMode?.mobile)


        pay_layout.selectedCallback = {
            updatePayType(it)
        }


        //updatePayType(PayManager.getDefaultPayStyle())

        tv_fine_protocol.onClick {
            WebViewActivity.startWebview(it.context, ConfigsKt.H5_PRO_FKZB())
        }

        //客服电话
//        img_float_service.setOnClickListener {
//
//            DialogFactory.showTelHelp(it.context,getString(R.string.fkdj_tel))
//
//        }

        //优惠券
        rl_coupon.onClick {

            startActivityForResult(ModuleActivity.getTargetIntent(it.context, ChooseCouponFragment.TAG).apply {
                putExtra(Constants.EXTRA_DATA_ID,fineViewModel.getFineLiveData().value?.couponId)
            },REQ_CHOOSE_COUPON)

        }

        //选择支付方式
//        rl_choose_pay_type.onClick {
//
//            choosePayType()
//
//        }

        fineViewModel.getFineLiveData().observe(this, Observer {
            it?.run {


                tv_service_fee.text = getString(R.string.amount_args,getServiceFeeText())
                tv_amount_mony.text = getString(R.string.amount_args,getTotalFeeText())


            }
        })

        //优惠卷
        fineViewModel.getCouponRespLiveData().observe(this, Observer {
            it?.run {
                if (isHidden){
                    return@Observer
                }
                if (isOk()){

                    showDefaultCouponTitle(data)

                }



            }
        })

        fineViewModel.getFinePayConfig().observe(this, Observer {

            it?.run {

                if (quickPayment){
                    group_fast_deal.visibility = View.VISIBLE
                }else{
                    group_fast_deal.visibility = View.GONE
                }
            }

        })


        fineViewModel.getOrderPayResultLiveData().observe(this, Observer {

            it?.run {

                if (status){
                    //支付成功
                    startPaySuccess()
                }

                fineViewModel.consumeOrderPayResult()
            }

        })

        fineViewModel.getAreaHintLiveData().observe(this, Observer {

            it?.let {msg ->

                if (!TextUtils.isEmpty(msg.trim())){

                    //提示
                    context?.run {
                        WarningDialog(this,msg).show()
                    }

                }
            }

        })

    }

//    private fun choosePayType(){
//
//       if ( PayManager.canChoosePayType()) {
//
//           context?.let {
//
//               val selectedPay = PayManager.getPayStyleMode(fineViewModel.getFineLiveData().value?.payStyle?:0)
//
//               ChoosePayTypeDialog(it, selectedPay) {
//
//                   updatePayType(it)
//
//               }.show()
//           }
//
//       }
//
//    }

    private fun startPaySuccess(){
        fineViewModel.saveFineNo(null)

        ModuleActivity.getTargetIntent(context, FKDJResultFragment.TAG).apply {
            putExtra("data", true)
        }.run {
            context?.startActivity(this)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK){


            when(requestCode){

                REQ_CHOOSE_COUPON -> {
                    //优惠卷

                    data?.getParcelableExtra<CouponModel?>(Constants.EXTRA_DATA)?.let {

                        tv_coupon_choose.text = getString(R.string.coupon_reduce,it.amountStr)
                        tv_coupon_choose.setTextColor(ContextCompat.getColor(tv_coupon_choose.context,R.color.accentColor3))
                        fineViewModel.getFineLiveData().value?.run {
                            couponId = it.id
                            setCouponFee(it.amount)
                        }
                    }?:kotlin.run {
                        showDefaultCouponTitle(fineViewModel.getCouponRespLiveData().value?.data)
                        fineViewModel.getFineLiveData().value?.run {
                            couponId = 0
                            setCouponFee("0")
                        }
                    }
                    fineViewModel.reSendFineData()
                    fineViewModel.countTotalFee()
                }

            }

        }
    }

    private fun checkPay(){

        fineViewModel.getFineLiveData().value?.run {


            if (fineNo.isNullOrEmpty() || fineNo?.length?:0 < 13){
                ToastUtils.showText("请输入13~16位处罚决定书编号")

                return
            }

            if (fineName.isNullOrEmpty()){
                ToastUtils.showText("请输入被处罚人姓名")
                return
            }

            if (fineDate.isNullOrEmpty()){
                ToastUtils.showText("请选择处罚时间")
                return
            }

            if (!hasFineFee()){
                ToastUtils.showText("请输入处罚金额")
                return
            }

            if (!fromQuery() && photo.isNullOrEmpty()){
                ToastUtils.showText("请上传处罚决定书照片")
                return
            }


            FullHintAlertDialog(context!!)
                    .setDialogMessage( if(hasQuickFee()) R.string.fkdj_quick_pay_hint1 else R.string.fkdj_pay_hint1,
                            R.string.fkdj_pay_hint2)
                    .setDelayNext(5)
                    .setLeftText(R.string.think_about, null)
                    .setRightText(R.string.continue_pay) {
                        startPay()

//                        requestOrder()
//                        fetchPayStr(payStyle, content, name, phone, orderMuch.toString(), bigFree.toString(), orderDate, img)
                        StatTools.sendClick(context, StatisticsId.clickFKDJ_Pay)
                    }.show()
        }


    }



    private fun startPay(){

        val fineData = fineViewModel.getFineLiveData().value?:return

        val value = object : ProgressDialogObserver<PaymentOrder>(context, "提示", "正在调起支付") {

            override fun onApiResult(map: PaymentOrder?) {
//                if (map != null && map.containsKey("pay")) {
//                    requestPay(payStyle, map["pay"])
//                }
//                if (map != null && map.containsKey("orderNo")) {
//                    orderNo = map["orderNo"]
//                }

                map?.run {


                    if (isSuccess){
                        activity?.let {act ->
                            if (!isFinish){
                                payStyle = fineData.payStyle
                                bizType = "fkdj"

                                fineViewModel.startPay(act,this)

                                //成功，清除缓存
                                ImageUtils.clearCache()
                            }
                        }
                    }else{
                        ToastUtils.showText("请求支付失败，请重试")
                    }

                }

            }

            override fun onApiError(result: BaseResult<*>?) {
                toastErrorMsg(result)
            }
        }


        if (!fineData.photo.isNullOrEmpty()){

            Single.just<File>(File(fineData.photo)).observeOn(Schedulers.io()).map { file ->

                ImageUtils.compress(file.absolutePath)
            }.flatMap {

                val key = "image"

                Api.get().uploadFiles("fkdj", mapOf(key to it)).map {
                    it.get(key)?.objectKey
                }

            }.flatMap { file ->

                val tel = DataCenter.get().userMode?.mobile

                Api.get().submitFKDJMode(fineData.fineNo!!,
                        fineData.fineName!!,
                        tel!!,
                        fineData.fineFee.toString(),
                        fineData.serviceFee.toString(),
                        fineData.fineDate,
                        fineData.payStyle.toString(),
                        file,fineData.hasQuickFee(),false,fineData.couponId)
            }
                    .subscribe(
                            value)


        }else{
            val tel = DataCenter.get().userMode?.mobile

            Api.get().submitFKDJMode(fineData.fineNo!!,
                    fineData.fineName!!,
                    tel!!,
                    fineData.fineFee.toString(),
                    fineData.serviceFee.toString(),
                    fineData.fineDate,
                    fineData.payStyle.toString(),
                    null,fineData.hasQuickFee(),true,fineData.couponId)
                    .subscribe(value)
        }

    }



    private fun updatePayType(payStyle:PayStyleModel?){

        payStyle?.let {

//            tv_pay_type.text = it.title
//
//            img_pay_icon.setImageResource(it.drawableId)

            fineViewModel.getFineLiveData().value?.payStyle = it.code

        }

    }

    private fun showBackDialog() {
        FullHintAlertDialog(context!!)
                .setDialogMessage(R.string.fkdj_back_hint)
                .setLeftText(R.string.reject_next) { finish() }
                .setRightText(R.string.after_see, null)
                .show()

    }


    private fun showDefaultCouponTitle(data: CouponResp?){

        if (data == null){
            rl_coupon.visibility = View.GONE
            return
        }

        if (fineViewModel.getFineLiveData().value?.hasCouponFee() == true){
            return
        }

        rl_coupon.visibility = View.VISIBLE

        val context = rl_coupon.context



        if (data.list.isNullOrEmpty()){
            //没有优惠券

            if (TextUtils.isEmpty(data.activityModel?.name)) {
                //也没有活动
                tv_coupon_choose.text = "无可用优惠券"
            }else{
                tv_coupon_choose.text = data.activityModel?.name
            }
            tv_coupon_choose.setTextColor(ContextCompat.getColor(context,R.color.textColorPrimary))
        }else{
            //有优惠券
            tv_coupon_choose.setTextColor(ContextCompat.getColor(context,R.color.accentColor3))
            tv_coupon_choose.text = getString(R.string.coupon_available,data.list.size)
        }

    }

//    override fun onBackPress(): Boolean {
//        showBackDialog()
//        return true
//    }


}